import configAll from "../../../config/configAll";
import { getFilePath, showToast } from './common'

function uploadFileRequest(file, callback) {
  uni.uploadFile({
    url: `${configAll.baseURL}/common/upload`, // 仅为示例，非真实的接口地址
    filePath: file.path,
    name: 'file',
    formData: {
      type: 9,
    },
    success: (uploadFileRes) => {
      console.log('uploadFileRes --->', uploadFileRes);
      try {
        const data = JSON.parse(uploadFileRes.data);
        callback({
          url: getFilePath(data.fileName),
          size: file.size,
          name: file.name,
        })
      } catch (error) {
        showToast(error.message)
      }
    }
  });
}

// 选择上传图片
export function uploadImage(callback, sourceType = 'album') {
  uni.chooseImage({
    count: 1, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: [sourceType], // 从相册选择
    success: (res) => {
      console.log('res ---->', res)
      const file = res.tempFiles[0];
      uploadFileRequest(file, callback);
    },
    fail: (error) => {
      console.log('error ---->', error)
      showToast(error?.message)
    }
  })
}

function validateFileType(fileName, types) {
  return types.some((type) => fileName.endsWith(type));
}

// 选择上传文件
export function uploadFile(callback) {
  wx.chooseMessageFile({
    count: 1, // 默认9
    type: 'file',
    success: (res) => {
      const file = res.tempFiles[0];
      const fileName = file.name.toLowerCase();
      if (!validateFileType(fileName, ['.doc', '.docx', '.pdf'])) {
        wx.showToast({
          title: '请选择doc/docx或pdf文件',
          icon: 'none'
        });
        return;
      }
      uploadFileRequest(file, callback);
    },
    fail: (error) => {
      console.log('error ---->', error)
      showToast(error?.message)
    }
  })
}
